package linklist

import "errors"

//单链表

//链表节点
type SingleNode struct {
	data interface{}
	next *SingleNode
}

//链表
type SingleNodeList struct {
	head *SingleNode
	size uint
}

func NewLinkList() *SingleNodeList {
	return &SingleNodeList{
		head: &SingleNode{0, nil},
		size: 0,
	}
}

//下一个节点
func (this *SingleNode) GetNext() *SingleNode {
	return this.next
}

//获取当前节点的值
func (this *SingleNode) GetValue() interface{} {
	return this.data
}

//插入节点
func (this *SingleNodeList) Insert(i uint, node *SingleNode) error {
	if i < 0 || node == nil || i > this.size {
		return errors.New("索引不合法")
	}

	//找到第i个节点
	preItem := this.head
	for j := uint(0); j < i; j++ {
		preItem = preItem.next
	}

	node.next = preItem.next
	preItem.next = node
	this.size++

	return nil
}

//删除节点
func (this *SingleNodeList) Delete(i uint) error {
	if i < 0 || i > this.size {
		return errors.New("索引不合法")
	}

	//找到第i-1个节点
	preItem := this.head
	for j := uint(0); j < i-1; j++ {
		preItem = preItem.next
	}

	preItem.next = preItem.next.next

	return nil
}
